﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Web.UI.WebControls;
using Module;
using Module.QuanLyDuoc.HeThongNhapXuat;

namespace HospitalManager.QuanLyDuoc.HeThongTaiChinh.ThanhToanHoaDon
{
    public partial class ThanhToanPhieuXuatKhoSangKho : System.Web.UI.Page
    {
        private const int PageSize = 20;
        private readonly PhieuXuatKhoSangKho _phieuXuatBanLe = new PhieuXuatKhoSangKho();
        private readonly SelectAllClass _selectAllClass = new SelectAllClass();
        private int _totalrow;

        protected void Page_Load(object sender, EventArgs e)
        {
            var loaiphieu = Request.QueryString["loaiphieu"];
            ClientScript.RegisterClientScriptBlock(typeof(string), "activeli", "$(function(){$('#" + loaiphieu + "').addClass('active')});", true);
            if (IsPostBack) return;
            if (Session["username"] == null)
            {
                Response.RedirectToRoute("DangNhap");
            }
            txtTuNgay.Text = DateTime.Now.ToString("dd-MM-yyyy");
            txtDenNgay.Text = DateTime.Now.ToString("dd-MM-yyyy");
            LoadKhoByKhoa();
            LoadPage();
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            ViewState["CheckRefresh"] = Session["CheckRefresh"];
        }

        private void LoadKhoByKhoa()
        {
            ddlKho_Khoa.DataSource = Session["superadmin"].ToString().Equals("true")
                ? _selectAllClass.SelectAllKho()
                : _selectAllClass.SelectKhoByKhoa(Session["makhoa"].ToString());
            ddlKho_Khoa.DataTextField = "TenKho";
            ddlKho_Khoa.DataValueField = "MaKho";
            ddlKho_Khoa.DataBind();
            ddlKho_Khoa.Items.Insert(0, new ListItem("Chọn kho", ""));
        }

        private void LoadPage()
        {
            var tungay = Convert.ToDateTime(DateTime.ParseExact(txtTuNgay.Text, "dd-MM-yyyy", null).ToString("yyyy-MM-dd"));
            var denngay = Convert.ToDateTime(DateTime.ParseExact(txtDenNgay.Text, "dd-MM-yyyy", null).ToString("yyyy-MM-dd"));
            gvPhieuXuatKhoSangKho.DataSource = _phieuXuatBanLe.PhieuXuatKhoSangKho_SelectAll(tungay, denngay,
                ddlKho_Khoa.SelectedValue, Convert.ToInt32(hfPageIndex.Value.Trim()),
                PageSize, out _totalrow)
                .AsEnumerable()
                .Where(x => x.Field<Byte>("IsXetDuyet") == 1 || x.Field<Byte>("IsXetDuyet") == 2)
                .Select(x => x)
                .AsDataView();
            gvPhieuXuatKhoSangKho.DataBind();
            GeneratePager(_totalrow, PageSize, Convert.ToInt32(hfPageIndex.Value.Trim()));
            Session["CheckRefresh"] = Server.UrlEncode(DateTime.Now.ToString(CultureInfo.InvariantCulture));
        }

        protected void dlPager_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName != "PageNo") return;
            hfPageIndex.Value = e.CommandArgument.ToString();
            LoadPage();
            e.Item.Attributes.Add("disabled", "disabled");
        }

        public void GeneratePager(int totalRowCount, int pageSize, int currentPage)
        {
            const int totalLinkInPage = 4;
            var totalPageCount = (int)Math.Ceiling((decimal)totalRowCount / pageSize);

            var startPageLink = Math.Max(currentPage - (int)Math.Floor((decimal)totalLinkInPage / 2), 1);
            var lastPageLink = Math.Min(startPageLink + totalLinkInPage - 1, totalPageCount);

            if ((startPageLink + totalLinkInPage - 1) > totalPageCount)
            {
                lastPageLink = Math.Min(currentPage + (int)Math.Floor((decimal)totalLinkInPage / 2), totalPageCount);
                startPageLink = Math.Max(lastPageLink - totalLinkInPage + 1, 1);
            }

            var pageLinkContainer = new List<ListItem>();

            if (startPageLink != 1)
            {
                pageLinkContainer.Add(new ListItem("«", "1", currentPage != 1));
            }
            for (var i = startPageLink; i <= lastPageLink; i++)
            {
                pageLinkContainer.Add(new ListItem(i.ToString(CultureInfo.InvariantCulture),
                    i.ToString(CultureInfo.InvariantCulture), currentPage != i));
            }
            if (lastPageLink != totalPageCount)
                pageLinkContainer.Add(new ListItem("»", totalPageCount.ToString(CultureInfo.InvariantCulture),
                    currentPage != totalPageCount));

            dlPager.DataSource = pageLinkContainer;
            dlPager.DataBind();
        }

        protected void btnTimKiem_Click(object sender, EventArgs e)
        {
            hfPageIndex.Value = "1";
            LoadPage();
        }

        protected void btnDuyetPhieuXuatKhoSangKho_Click(object sender, EventArgs e)
        {
            if (Session["username"] == null)
            {
                Response.RedirectToRoute("DangNhap");
            }
            else
            {
                if (Session["CheckRefresh"].ToString() != ViewState["CheckRefresh"].ToString())
                {
                    LoadPage();
                }
                else
                {
                    var maphieu = ((LinkButton)sender).CommandArgument;
                    if (hfStatusPhieu.Value.Equals("1"))
                    {
                        _phieuXuatBanLe.PhieuXuatKhoSangKho_UpdateDuyetPhieu(maphieu, Session["username"].ToString(), (int)Application["ChuaDuyet"], hfStrTraPhieu.Value);
                    }
                    else
                    {
                        _phieuXuatBanLe.PhieuXuatKhoSangKho_UpdateDuyetPhieu(maphieu, Session["username"].ToString(), (int)Application["DaDuyet"], "");
                    }
                    LoadPage();
                }
            }
        }

        protected void btnTraLaiPhieuXuatKhoSangKho_Click(object sender, EventArgs e)
        {
            if (Session["username"] == null)
            {
                Response.RedirectToRoute("DangNhap");
            }
            else
            {
                if (Session["CheckRefresh"].ToString() != ViewState["CheckRefresh"].ToString())
                {
                    LoadPage();
                }
                else
                {
                    var maphieunhap = ((LinkButton) sender).CommandArgument;
                    //Get the button that raised the event
                    var btn = (LinkButton) sender;
                    //Get the row that contains this button
                    var gvr = (GridViewRow) btn.NamingContainer;
                    //Get rowindex
                    var lydotra =
                        ((TextBox) gvPhieuXuatKhoSangKho.Rows[gvr.RowIndex].Cells[7].FindControl("txtGhiChu")).Text;
                    _phieuXuatBanLe.PhieuXuatKhoSangKho_UpdateDuyetPhieu(maphieunhap, Session["username"].ToString(),
                        (int) Application["ChuaDuyet"], lydotra);
                    LoadPage();
                }
            }
        }

        protected void gvPhieuXuatKhoSangKho_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType != DataControlRowType.DataRow) return;
            var status = Convert.ToInt32(((DataRowView)e.Row.DataItem)["IsXetDuyet"].ToString());
            if (status != 2) return;
            e.Row.Cells[7].FindControl("btnDuyetPhieuXuatKhoSangKho").Visible = false;
            e.Row.Cells[7].FindControl("btnDropDownTraLaiPhieuXuatKhoSangKho").Visible = false;
        }
    }
}